# -*- coding: utf8 -*-
import urllib
import urllib2
import sgmllib

 
class Translator:
    def __init__(self, langFrom = 'en', langTo = 'es'):
        self.url = 'http://translate.google.com/translate_t'
        self.headers = {
            'Host'              : 'translate.google.com',
            'User-Agent'        : 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.3) Gecko/20070309 Firefox/2.0.0.3',
            'Accept'            : 'text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5',
            'Accept-Language'   : 'es-ar,en-us;q=0.7,en;q=0.3',
            'Accept-Charset'    : 'ISO-8859-1,utf-8;q=0.7,*;q=0.7',
            'Keep-Alive'        : '300',
            'Connection'        : 'keep-alive',
            'Referer'           : 'http://translate.google.com/translate_t',
            'Content-Type'      : 'application/x-www-form-urlencoded'        
        }
 
        self.data = {
            'hl'        : 'es',
            'ie'        : 'UTF8',
            'langpair'  : '%s|%s' % (langFrom, langTo)
        }
 
    def translate(self, text):
        data = self.data.copy()
        data['text'] = text
 
        headers = self.headers.copy()
        headers['Content-Length'] = str(urllib.urlencode(data).count('') - 1)
 
        req = urllib2.Request(self.url, urllib.urlencode(data), headers)
        res = urllib2.urlopen(req)
 
        responseText = res.read()
 
        translation = responseText.split('<div id=result_box dir=ltr>')[1].split('</div>')[0]
 
        return unicode(translation.strip(), 'utf-8')

    def translate(self, text):
        data = self.data.copy()
        data['text'] = text
 
        headers = self.headers.copy()
        headers['Content-Length'] = str(urllib.urlencode(data).count('') - 1)
 
        req = urllib2.Request(self.url, urllib.urlencode(data), headers)
        res = urllib2.urlopen(req)
 
        responseText = res.read()
 
        translation = responseText.split('<div id=result_box dir=ltr>')[1].split('</div>')[0]
 
        return unicode(translation.strip(), 'utf-8')

    def availableLanguages(self, text):
        data = self.data.copy()
        data['text'] = text
 
        headers = self.headers.copy()
        headers['Content-Length'] = str(urllib.urlencode(data).count('') - 1)
 
        req = urllib2.Request(self.url, urllib.urlencode(data), headers)
        res = urllib2.urlopen(req)
 
        responseText = res.read()
 
        translation = responseText.split('<div id=result_box dir=ltr>')[1].split('</div>')[0]
 
        return unicode(translation.strip(), 'utf-8')

if __name__ == '__main__':
    t = Translator()
    print t.translate('hello')

